<template>
  <div class="messages-container">
    <div class="messages-header">
      <h2>消息中心</h2>
      <div class="header-actions">
        <button class="action-btn mark-read" @click="markAllAsRead">
          <span>全部标记为已读</span>
        </button>
        <button class="action-btn refresh" @click="refreshMessages">
          <span>刷新</span>
        </button>
      </div>
    </div>

    <div class="messages-filter">
      <div class="filter-item">
        <label>消息类型</label>
        <select v-model="filters.type">
          <option value="all">全部类型</option>
          <option v-for="type in messageTypes" :key="type.value" :value="type.value">{{ type.label }}</option>
        </select>
      </div>
      <div class="filter-item">
        <label>消息状态</label>
        <select v-model="filters.status">
          <option value="all">全部状态</option>
          <option value="unread">未读</option>
          <option value="read">已读</option>
        </select>
      </div>
      <div class="filter-item">
        <label>时间范围</label>
        <select v-model="filters.timeRange">
          <option value="all">全部时间</option>
          <option value="today">今天</option>
          <option value="week">本周</option>
          <option value="month">本月</option>
        </select>
      </div>
    </div>

    <div class="messages-content">
      <div class="messages-list">
        <div
            v-for="message in filteredMessages"
            :key="message.id"
            :class="['message-item', { unread: !message.read, important: message.priority === 'high' }]"
            @click="selectMessage(message)"
        >
          <div class="message-icon">
            <span v-if="message.type === 'system'">📢</span>
            <span v-else-if="message.type === 'exam'">📝</span>
            <span v-else-if="message.type === 'approval'">✅</span>
            <span v-else-if="message.type === 'alert'">⚠️</span>
            <span v-else>✉️</span>
          </div>
          <div class="message-info">
            <div class="message-header">
              <h3 class="message-title">{{ message.title }}</h3>
              <span class="message-time">{{ formatTime(message.time) }}</span>
            </div>
            <p class="message-preview">{{ truncateText(message.content, 50) }}</p>
            <div class="message-meta">
              <span class="message-sender">{{ message.sender }}</span>
              <span class="message-type">{{ getMessageTypeLabel(message.type) }}</span>
            </div>
          </div>
          <div v-if="!message.read" class="unread-badge"></div>
        </div>
      </div>

      <div class="message-detail" v-if="selectedMessage">
        <div class="detail-header">
          <h3 class="detail-title">{{ selectedMessage.title }}</h3>
          <div class="detail-actions">
            <button v-if="!selectedMessage.read" class="action-btn mark-read" @click.stop="markAsRead(selectedMessage)">
              标记为已读
            </button>
            <button class="action-btn delete" @click.stop="deleteMessage(selectedMessage)">
              删除
            </button>
            <button class="action-btn close" @click="selectedMessage = null">
              ×
            </button>
          </div>
        </div>

        <div class="detail-meta">
          <div class="meta-item">
            <span class="meta-label">发件人：</span>
            <span class="meta-value">{{ selectedMessage.sender }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">时间：</span>
            <span class="meta-value">{{ formatFullTime(selectedMessage.time) }}</span>
          </div>
          <div class="meta-item">
            <span class="meta-label">类型：</span>
            <span class="meta-value">{{ getMessageTypeLabel(selectedMessage.type) }}</span>
          </div>
        </div>

        <div class="detail-content">
          <p>{{ selectedMessage.content }}</p>

          <div v-if="selectedMessage.attachment" class="attachments">
            <h4>附件</h4>
            <div class="attachment-item">
              <span class="attachment-name">{{ selectedMessage.attachment.name }}</span>
              <button class="download-btn" @click="downloadAttachment(selectedMessage.attachment)">
                下载
              </button>
            </div>
          </div>
        </div>

        <div class="detail-footer">
          <button class="reply-btn" @click="replyToMessage(selectedMessage)">
            回复
          </button>
        </div>
      </div>

      <div v-else class="empty-detail">
        <div class="empty-content">
          <span class="empty-icon">📭</span>
          <p>请从左侧列表选择一条消息查看详情</p>
        </div>
      </div>
    </div>

    <div class="messages-pagination">
      <span>总共 {{ totalMessages }} 条消息</span>
      <div class="pagination-controls">
        <button v-for="page in pageCount" :key="page"
                :class="['page-btn', currentPage === page ? 'active' : '']"
                @click="currentPage = page">
          [{{ page }}]
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue';

// 消息类型定义
interface Message {
  id: number;
  title: string;
  content: string;
  sender: string;
  time: Date;
  type: string; // 'system', 'exam', 'approval', 'alert', 'other'
  read: boolean;
  priority: string; // 'low', 'medium', 'high'
  attachment?: {
    name: string;
    size: string;
  };
}

// 消息类型选项
const messageTypes = ref([
  { value: 'system', label: '系统通知' },
  { value: 'exam', label: '监考安排' },
  { value: 'approval', label: '审批通知' },
  { value: 'alert', label: '紧急提醒' },
  { value: 'other', label: '其他消息' }
]);

// 筛选条件
const filters = reactive({
  type: 'all',
  status: 'all',
  timeRange: 'all'
});

// 分页控制
const currentPage = ref(1);
const itemsPerPage = 8;

// 模拟消息数据
const messages = ref<Message[]>([
  {
    id: 1,
    title: '2023年下半年监考安排已发布',
    content: '2023年下半年研究生招生考试监考安排已经发布，请登录系统查看您的监考任务，并按时参加监考培训。',
    sender: '研究生招生办公室',
    time: new Date(2023, 5, 15, 14, 30),
    type: 'exam',
    read: false,
    priority: 'high'
  },
  {
    id: 2,
    title: '张老师的监考报名已通过',
    content: '张老师（工号：10001）的2023年6月研究生监考报名已通过审核，请通知相关教师。',
    sender: '审批系统',
    time: new Date(2023, 5, 14, 9, 15),
    type: 'approval',
    read: true,
    priority: 'medium'
  },
  {
    id: 3,
    title: '系统维护通知',
    content: '监考管理系统将于2023年6月20日（周二）凌晨2:00-4:00进行系统维护，届时系统将无法访问，请提前安排好工作。',
    sender: '系统管理员',
    time: new Date(2023, 5, 13, 16, 45),
    type: 'system',
    read: false,
    priority: 'medium'
  },
  {
    id: 4,
    title: '监考费用结算提醒',
    content: '2023年5月监考费用已结算，请各位老师及时查收。如有疑问，请联系财务处李老师（电话：028-12345678）。',
    sender: '财务处',
    time: new Date(2023, 5, 12, 11, 20),
    type: 'other',
    read: false,
    priority: 'low'
  },
  {
    id: 5,
    title: '监考培训材料更新',
    content: '研究生监考培训材料已更新，新增了关于考场纪律处理的最新规定，请所有监考老师下载学习。附件为最新培训材料。',
    sender: '考务科',
    time: new Date(2023, 5, 10, 15, 10),
    type: 'exam',
    read: true,
    priority: 'high',
    attachment: {
      name: '2023年监考培训手册.pdf',
      size: '2.5MB'
    }
  },
  {
    id: 6,
    title: '紧急：考场调整通知',
    content: '因考场安排冲突，原定于2023年6月25日在南湖校区3号教学楼201教室的考试调整至301教室，请通知相关监考老师和考生。',
    sender: '研究生招生办公室',
    time: new Date(2023, 5, 9, 17, 30),
    type: 'alert',
    read: false,
    priority: 'high'
  },
  {
    id: 7,
    title: '李老师的监考申请被驳回',
    content: '李老师（工号：10002）的监考申请因材料不完整被驳回，请通知该老师补充材料后重新提交申请。',
    sender: '审批系统',
    time: new Date(2023, 5, 8, 10, 5),
    type: 'approval',
    read: true,
    priority: 'medium'
  },
  {
    id: 8,
    title: '监考经验分享会邀请',
    content: '研究生院将于2023年6月30日举办监考经验分享会，邀请有经验的监考老师分享监考技巧和应急处理方法，欢迎各位老师参加。',
    sender: '研究生院',
    time: new Date(2023, 5, 7, 14, 55),
    type: 'other',
    read: false,
    priority: 'low'
  },
  {
    id: 9,
    title: '系统登录安全升级',
    content: '为提升系统安全性，监考管理系统已升级登录验证机制，请各位老师使用新版系统登录方式。',
    sender: '系统管理员',
    time: new Date(2023, 5, 6, 9, 30),
    type: 'system',
    read: true,
    priority: 'medium'
  },
  {
    id: 10,
    title: '监考反馈表提交提醒',
    content: '请各位监考老师在完成监考任务后3个工作日内提交监考反馈表，以便我们及时改进监考工作。',
    sender: '考务科',
    time: new Date(2023, 5, 5, 16, 20),
    type: 'exam',
    read: true,
    priority: 'medium'
  }
]);

// 当前选中的消息
const selectedMessage = ref<Message | null>(null);

// 获取消息类型标签
function getMessageTypeLabel(type: string): string {
  const typeObj = messageTypes.value.find(t => t.value === type);
  return typeObj ? typeObj.label : '其他消息';
}

// 过滤后的消息
const filteredMessages = computed(() => {
  let result = messages.value;

  // 按类型过滤
  if (filters.type !== 'all') {
    result = result.filter(msg => msg.type === filters.type);
  }

  // 按状态过滤
  if (filters.status !== 'all') {
    const isUnread = filters.status === 'unread';
    result = result.filter(msg => msg.read !== isUnread);
  }

  // 按时间范围过滤
  if (filters.timeRange !== 'all') {
    const now = new Date();
    let startDate: Date;

    switch (filters.timeRange) {
      case 'today':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        break;
      case 'week':
        const day = now.getDay(); // 0 = 周日
        const diff = now.getDate() - day + (day === 0 ? -6 : 1); // 周一的日期
        startDate = new Date(now.setDate(diff));
        break;
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        break;
      default:
        return result;
    }

    result = result.filter(msg => msg.time >= startDate);
  }

  // 分页处理
  const startIndex = (currentPage.value - 1) * itemsPerPage;
  return result.slice(startIndex, startIndex + itemsPerPage);
});

// 总消息数
const totalMessages = computed(() => {
  return messages.value.length;
});

// 总页数
const pageCount = computed(() => {
  return Math.ceil(totalMessages.value / itemsPerPage);
});

// 格式化时间
function formatTime(date: Date): string {
  const now = new Date();
  const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));

  if (diffDays === 0) {
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  } else if (diffDays === 1) {
    return '昨天';
  } else if (diffDays < 7) {
    return `${diffDays}天前`;
  } else {
    return date.toLocaleDateString([], { month: '2-digit', day: '2-digit' });
  }
}

// 完整格式化时间
function formatFullTime(date: Date): string {
  return date.toLocaleString([], {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 截断文本
function truncateText(text: string, maxLength: number): string {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
}

// 选择消息
function selectMessage(message: Message) {
  selectedMessage.value = message;
  if (!message.read) {
    message.read = true;
  }
}

// 标记为已读
function markAsRead(message: Message) {
  message.read = true;
}

// 标记所有为已读
function markAllAsRead() {
  messages.value.forEach(msg => {
    msg.read = true;
  });
}

// 删除消息
function deleteMessage(message: Message) {
  const index = messages.value.findIndex(m => m.id === message.id);
  if (index !== -1) {
    messages.value.splice(index, 1);
    if (selectedMessage.value && selectedMessage.value.id === message.id) {
      selectedMessage.value = null;
    }
  }
}

// 下载附件
function downloadAttachment(attachment: { name: string; size: string }) {
  alert(`开始下载附件: ${attachment.name}`);
  // 实际项目中这里会有下载逻辑
}

// 回复消息
function replyToMessage(message: Message) {
  alert(`回复给: ${message.sender}`);
  // 实际项目中这里会有回复逻辑
}

// 刷新消息
function refreshMessages() {
  // 模拟刷新消息
  alert('消息已刷新');
}
</script>

<style scoped>
.messages-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.messages-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eaeaea;
}

.messages-header h2 {
  margin: 0;
  color: #1a2b4b;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.mark-read {
  background-color: #e6f7ff;
  color: #1890ff;
}

.mark-read:hover {
  background-color: #bae7ff;
}

.refresh {
  background-color: #f0f9eb;
  color: #67c23a;
}

.refresh:hover {
  background-color: #e1f3d8;
}

.messages-filter {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.filter-item {
  flex: 1;
}

.filter-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #555;
}

.filter-item select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
}

.messages-content {
  display: flex;
  gap: 20px;
  min-height: 500px;
  margin-bottom: 20px;
}

.messages-list {
  flex: 0 0 40%;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow-y: auto;
  max-height: 500px;
}

.message-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #f0f2f5;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.message-item:hover {
  background-color: #f8fafc;
}

.message-item.unread {
  background-color: #f0f9ff;
}

.message-item.important {
  border-left: 4px solid #ff4d4f;
}

.message-icon {
  flex: 0 0 40px;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-info {
  flex: 1;
  min-width: 0;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.message-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a2b4b;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

.message-preview {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-meta {
  display: flex;
  gap: 10px;
  font-size: 12px;
  color: #999;
}

.message-sender {
  font-weight: 500;
}

.unread-badge {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 8px;
  height: 8px;
  background-color: #1890ff;
  border-radius: 50%;
}

.message-detail, .empty-detail {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eaeaea;
}

.detail-title {
  margin: 0;
  font-size: 18px;
  color: #1a2b4b;
  font-weight: 600;
  flex: 1;
}

.detail-actions {
  display: flex;
  gap: 10px;
}

.detail-actions .action-btn {
  padding: 6px 12px;
  font-size: 13px;
}

.detail-actions .mark-read {
  background-color: #e6f7ff;
  color: #1890ff;
}

.detail-actions .delete {
  background-color: #fff1f0;
  color: #f5222d;
}

.detail-actions .close {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-actions .close:hover {
  background-color: #f5f5f5;
  border-radius: 50%;
}

.detail-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f2f5;
  font-size: 14px;
}

.meta-item {
  display: flex;
}

.meta-label {
  color: #555;
  font-weight: 500;
}

.meta-value {
  color: #1a2b4b;
}

.detail-content {
  flex: 1;
  margin-bottom: 20px;
  line-height: 1.6;
}

.attachments {
  margin-top: 25px;
  padding-top: 15px;
  border-top: 1px dashed #eaeaea;
}

.attachments h4 {
  margin: 0 0 15px 0;
  color: #1a2b4b;
  font-size: 16px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f8fafc;
  border-radius: 4px;
  border: 1px solid #eaeaea;
}

.attachment-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.download-btn {
  padding: 5px 10px;
  background-color: #1a3a6c;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.download-btn:hover {
  background-color: #2c5282;
}

.detail-footer {
  display: flex;
  justify-content: flex-end;
}

.reply-btn {
  padding: 8px 20px;
  background-color: #1a3a6c;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.reply-btn:hover {
  background-color: #2c5282;
}

.empty-detail {
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-content {
  text-align: center;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  display: block;
  margin-bottom: 15px;
}

.messages-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  font-size: 14px;
  color: #666;
}

.pagination-controls {
  display: flex;
  gap: 5px;
}

.page-btn {
  padding: 5px 10px;
  background-color: #f0f2f5;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.page-btn:hover {
  background-color: #e2e8f0;
}

.page-btn.active {
  background-color: #1a3a6c;
  color: white;
}
</style>